import React from 'react'
import { Form, Button, Input, TreeSelect, Select, DatePicker, message, Breadcrumb, Modal } from 'antd'
import $ from 'jquery'
import moment from 'moment'
import Config from '../../common/config'
import server from '../server'

const config = new Config()
const TreeNode = TreeSelect.TreeNode
const Option = Select.Option
const FormItem = Form.Item
const token = sessionStorage.getItem('token')
let UserInfo = sessionStorage.getItem('UserInfo')
UserInfo = UserInfo ? JSON.parse(UserInfo) : {}
const root = UserInfo.root
const auth = root ? {} : (UserInfo.auth ? (UserInfo.auth[server.serverName] || {}) : {})

class UserEditForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      rlTree: [],//角色树
      dpTree: [],//权限树
    };
  }
  componentWillMount() {
    return Promise.all([
      Promise.resolve($.ajax({
        url: `${config.Priviliege}/roles/tree`,
        type: "get",
        headers: { Authorization: 'Bearer ' + token },
      })),
      Promise.resolve($.ajax({
        url: `${config.Priviliege}/department/tree`,
        type: "get",
        headers: { Authorization: 'Bearer ' + token },
      }))
    ]).then(data => {
      // console.log(data)
      if (data[0].code == 200 && data[1].code == 200) {
        this.setState({
          rlTree: data[0].rl || [],
          dpTree: data[1].dp || []
        })
      } else {
        message.error('服务器繁忙')
      }
    }).catch(err => {
      console.log(err)
      message.error('发生错误')
    })
  }

  //生日禁用
  disabledDate(val) {
    if (val) {
      return val.valueOf() > Date.now();
    } else {
      return false;
    }
  }
  //验证员工账号
  validate(e) {
    const userName = e.target.value
    return Promise.resolve(
      $.ajax({
        type: 'post',
        url: config.Priviliege + '/user/verify',
        data: { userName },
        headers: { Authorization: 'Bearer ' + token },
      })
    ).then(code => {
      if (code == 201) {
        this.props.form.setFields({
          userName: { value: userName, errors: ['已存在的用户名'] }
        });
      } else if (code == 500) {
        message.error('服务器繁忙')
        this.props.form.setFields({
          userName: { value: userName, errors: ['验证失败'] }
        });
      }
    }).catch(err => {
      message.error('发生错误')
    })
  }
  //保存员工
  saveData() {
    this.props.form.validateFields((err, values) => {
      console.log(err, values);
      if (!err) {
        values.birthday && (values.birthday = values.birthday.format('YYYY-MM-DD HH:mm:ss'))
        values.rolesNumber = JSON.stringify(values.rolesNumber)
        console.log(values)
        return Promise.resolve(
          $.ajax({
            type: 'post',
            url: config.Priviliege + '/user/save',
            dataType: 'json',
            traditional: true,
            headers: { Authorization: 'Bearer ' + token },
            data: values,
          })
        ).then(res => {
          console.log(res)
          if (res.code == 200) {
            this.props.form.resetFields();
            message.success('新建成功');
            Modal.confirm({
              content: '是否返回员工列表页？',
              onCancel: () => {
                console.log('取消');
              },
              onOk: () => {
                window.location.hash = '/user';
              }
            });
          } else if (res.code == 201) {
            message.info(res.msg)
          } else {
            message.info('服务器繁忙')
          }
        }).catch(err => {
          console.log(err)
          message.error('发生错误')
        })
      }
    })
  }

  //取消保存
  cancelSave() {
    Modal.confirm({
      title: '取消保存',
      content: '确认取消保存并返回员工列表页面吗？',
      onCancel: () => {
        console.log('取消');
      },
      onOk: () => {
        window.location.hash = '/user';
      }
    });
  }

  //生成树选择组件
  nodeTree(arr) {
    return arr.map(value => {
      return <TreeNode
        value={value.number}
        key={value.number}
        title={value.name}
      >
        {
          value.children && this.nodeTree(value.children)
        }
      </TreeNode>
    })
  }

  rolesChange(value, label, extra) {
    const { setFieldsValue } = this.props.form
    if (extra.selected) {
      const newNumber = extra.triggerValue
      const newValue = value.filter(
        roleNumber => {
          return !(roleNumber.includes(newNumber + '-') || newNumber.includes(roleNumber + '-'))
        }
      )
      value.splice(0, value.length)
      value.push(...newValue)
    }
  }
  render() {
    const { detail, rlTree, dpTree } = this.state
    const formItemLayout = { labelCol: { span: 6 }, wrapperCol: { span: 18 } };
    const { getFieldDecorator } = this.props.form;
    return (
      <div className="container">
        <div className="box" style={{ maxWidth: 1000 }}>
          <div className="goods-label-cont-nav clearfix" style={{ position: 'relative' }}>
            <Breadcrumb separator=">">
              <Breadcrumb.Item>权限管理</Breadcrumb.Item>
              <Breadcrumb.Item><span className='separator-a'>员工管理</span></Breadcrumb.Item>
              <Breadcrumb.Item><span className='separator-a'>新增员工</span></Breadcrumb.Item>
            </Breadcrumb>
          </div>
          <div className="employeeRow">
            <FormItem {...formItemLayout} label="用户名" style={{ display: 'inline-block', width: '50%' }}>
              {getFieldDecorator('userName', {
                rules: [
                  { whitespace: false },
                  { max: 20, message: '长度不能超过20' },
                  { required: true, message: '用户名不能为空' },
                  { pattern: /^[a-zA-Z0-9\u4e00-\u9fa5]+$/, message: '用户名只能为中文、字母、数字' }
                ],
              })(<Input
                placeholder='请输入用户名'
                onBlur={this.validate.bind(this)}
                onChange={(e) => { e.target.value = $.trim(e.target.value).replace(' ', '') }}
              />)}
            </FormItem>
            <FormItem {...formItemLayout} label="密码" style={{ display: 'inline-block', width: '50%' }}>
              {getFieldDecorator('password', {
                rules: [
                  { pattern: /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d).{8,}$/, message: '密码必须包含大、小写字母和数字、长度不小于8;' },
                  { max: 20, message: '长度不能超过20' },
                  { required: true, message: '密码不能为空' },
                ],
              })(
                <Input
                  placeholder='请输入密码'
                  type='password'
                  onChange={(e) => { e.target.value = $.trim(e.target.value).replace(' ', '') }}
                />
              )}
            </FormItem>
          </div>
          <div className="employeeRow">
            <FormItem {...formItemLayout} label="姓名" style={{ display: 'inline-block', width: '50%' }}>
              {getFieldDecorator('name', {
                rules: [
                  { max: 5, message: '长度不能超过5' },
                  { required: true, message: '姓名不能为空' },
                  { pattern: /^[a-zA-Z0-9\u4e00-\u9fa5]+$/, message: '姓名只能为中文、字母、数字' }
                ],
              })(<Input
                placeholder='请输入姓名'
                onChange={(e) => { e.target.value = $.trim(e.target.value) }}
              />)}
            </FormItem>
            <FormItem {...formItemLayout} label="性别" style={{ display: 'inline-block', width: '50%' }}>
              {getFieldDecorator('gender', {
                rules: [
                  { required: true, message: '性别不能为空' },
                ],
                initialValue: 'true'
              })(
                <Select style={{ width: '100px' }} placeholder='请选择性别' >
                  <Option value='true'>男</Option>
                  <Option value='false'>女</Option>
                </Select>
              )}
            </FormItem>
          </div>
          <div className="employeeRow">
            <FormItem {...formItemLayout} label="电话号码" style={{ display: 'inline-block', width: '50%' }}>
              {getFieldDecorator('phone', {
                rules: [
                  { required: true, message: '电话号码不能为空' },
                  { pattern: /^(\d){11}$/, message: '请输入正确的手机号' }
                ],
              })(<Input
                placeholder='请输入电话号码'
                onChange={(e) => { e.target.value = $.trim(e.target.value).replace(' ', '') }}
              />)}
            </FormItem>
            <FormItem {...formItemLayout} label="生日" style={{ display: 'inline-block', width: '50%' }}>
              {getFieldDecorator('birthday', {
              })(
                <DatePicker
                  format="YYYY-MM-DD"
                  placeholder='请选择生日'
                  disabledDate={(val) => this.disabledDate(val)}
                  style={{ width: 230 }}
                />
              )}
            </FormItem>
          </div>
          <div className="employeeRow">
            <FormItem {...formItemLayout} label="qq号" style={{ display: 'inline-block', width: '50%' }}>
              {getFieldDecorator('qq', {
                rules: [
                  { max: 15, message: '长度不能超过15' },
                  { pattern: /^(\d)*$/, message: '请输入正确的qq号' }
                ],
              })(<Input
                placeholder="请输入qq号"
                onChange={(e) => { e.target.value = $.trim(e.target.value).replace(' ', '') }}
              />)}
            </FormItem>
            <FormItem {...formItemLayout} label="状态" style={{ display: 'inline-block', width: '50%' }}>
              {getFieldDecorator('status', {
                rules: [{ required: true, message: '请选择状态' }],
              })(
                <Select style={{ width: 120 }} placeholder="状态">
                  <Option value="1">在职</Option>
                  <Option value="2">试用</Option>
                  <Option value="0">离职</Option>
                </Select>
              )}
            </FormItem>
          </div>
          <div className="employeeRow">
            <FormItem labelCol={{ span: 3 }} wrapperCol={{ span: 21 }} label="部门">
              {getFieldDecorator('departmentNumber', {
                rules: [{ required: true, message: '请选择部门' }],
              })(
                <TreeSelect
                  showSearch
                  treeNodeFilterProp='title'
                  style={{ width: 300 }}
                  dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                  placeholder="请选择"
                  searchPlaceholder="搜索"
                  allowClear
                  treeDefaultExpandAll
                >
                  {
                    this.nodeTree(dpTree)
                  }
                </TreeSelect>
              )}
            </FormItem>
          </div>
          <div className="employeeRow">
            <FormItem labelCol={{ span: 3 }} wrapperCol={{ span: 21 }} label="角色">
              {getFieldDecorator('rolesNumber', {
                rules: [{ required: true, message: '请选择角色' }],
              })(
                <TreeSelect
                  treeNodeFilterProp='title'
                  treeCheckStrictly={true}
                  style={{ width: 300 }}
                  dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                  placeholder="请选择"
                  searchPlaceholder="搜索"
                  multiple={true}
                  allowClear
                  treeDefaultExpandAll
                  onChange={this.rolesChange.bind(this)}
                >
                  {
                    this.nodeTree(rlTree)
                  }
                </TreeSelect>
              )}
            </FormItem>
          </div>
          <div className="employeeRow">
            <FormItem labelCol={{ span: 3 }} wrapperCol={{ span: 21 }} label="备注">
              {getFieldDecorator('remark', {
                rules: [
                  { max: 200, message: '长度不能超过200' },
                  { pattern: /^[a-zA-Z\u4e00-\u9fa5\d'"\\?,.，。；;!:()‘’“” ]+$/, message: '只能为中文、字母、数字' }
                ],
              })(<Input
                type="textarea"
                style={{ resize: 'none' }}
                rows={3}
                placeholder="请输入备注"
                onChange={(e) => { e.target.value = $.trim(e.target.value) }}
              />)}
            </FormItem>
          </div>
          <div style={{ textAlign: 'right', marginTop: 10 }}>
            {
              (root || auth['/user/save']) ?
                <Button
                  type="primary"
                  style={{ marginRight: 15 }}
                  onClick={this.saveData.bind(this)}
                >保存</Button>
                : ''
            }
            <Button onClick={this.cancelSave.bind(this)}>取消</Button>
          </div>
        </div>
      </div>
    );
  }
}
const UserEdit = Form.create()(UserEditForm);
export default UserEdit;
